#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);
use SIM_settings;
use SIM_base;
use SIM_nodeInfo;
use SIM_updateInfo;
use SIM_cgiSettings;

# Startupscript casetool, part of Sipman.

my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];


my $backHeader="black";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $updateTool = $ENV{'SIM_UPDATET'} || die "No env SIM_UPDATET found.";
my $sharedConfDir = $ENV{'SIM_SHAREDCONFD'} || die "Oops no env found for SIM_SHAREDCONFD.";


sub printMainMenu {
  my $fontColor = "#222222";
  print("<TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR><TD BGCOLOR=#EEEEEE><CENTER>
    <A HREF=$httpScriptName?$module+$tool+importArp><FONT COLOR=$fontColor>arpInfo</FONT></A> |
    <A HREF=$httpScriptName?$module+$tool+importIp><FONT COLOR=$fontColor>ipAddress</FONT></A> 
    </TD></TR></TABLE><CENTER>
        ");
}

sub importArp {
  my $seedList = param("seedList");
  if ( "$seedList" eq "" ) {
    print("Importing arp table (syntax xxxx ipaddr aaaa.bbbb.cccc).
      <FORM method=post Action=$httpScriptName?$module+$tool+importArp>
      <TEXTAREA NAME=\"seedList\" ROWS=20 COLS=100></TEXTAREA><BR>
      <INPUT TYPE=submit Value=\"Process\">
      </FORM>
          ");
  } else {
    my $now = time;
    my $outFile = "$SIMparam{'SIMimportArpPath'}-$now";
    print("Updating $outFile.");
    open( OUT, ">$outFile") || die ("Oops, could not create $outFile.");;
    print OUT $seedList;
    close OUT;
    print("<PRE></CENTER>");
    system(" $SIMparam{'SIMgetArpTool'} $SIMparam{'SIMimportArpPath'} ");
    print("</PRE>");
  }
}

sub importIp {
  my $seedList = param("seedList");
  my $nodeType = param("nodeType");
  my $pollStatus = param("pollStatus");
  my $managementType = param("managementType");
  my $recType = param("recType");
  my $importAction = param("action");
  if ( "$importAction" eq "" ) {
    print("<B>Enter your IP seedlist below</B> (any text is accepted as long as there is white space around the ip adresses):
       <FORM method=post Action=$httpScriptName?$module+$tool+importIp>
       <INPUT TYPE=hidden NAME=action VALUE=test> 
         <TEXTAREA NAME=\"seedList\" ROWS=20 COLS=100>
         </TEXTAREA><BR>
          <INPUT TYPE=submit Value=\"Process\">
       </FORM>
          ");
  } else {
    my @entries = split(' ', $seedList);
    if ( "$importAction" eq "test" ) {
      print("<FONT SIZE=+1><B>Selected nodes from the seedfile</B></FONT><BR>
             (if the list is not correct, use the back button to correct it.)<P><TABLE>");
    } elsif ( "$importAction" eq "sla" ) {
      print("</CENTER><PRE>");
    }
    my $num = 1;
    my $slaInfo;
#   print("seedList: $seedList<HR>");
    my $testList;
    foreach my $entry (@entries) {
#     print("entry=$entry, ");
      my $result = testIfIp( $entry );
#     print("result=$result, ");
      if ( "$result" eq "oke" ) {
#       print("<B>$entry</B>");
        if ( "$importAction" eq "import" ) {
          printDebug( 0, "Processing node $entry: ");
#         system (" $updateTool seedFile-$remoteUser addnode $entry ");
	  if ( "$nodeType" ne "" ) {
            #system (" $updateTool seedFile-$remoteUser modNodeType $entry $nodeType ");
            &setNodeType( $entry, "seedFile-$remoteUser", $nodeType );
	  }
          if ( "$recType" ne "" ) {
            #system (" $updateTool seedFile-$remoteUser modSipmanRectype $entry $recType");
            &setRecType( $entry, "seedFile-$remoteUser", $recType );
          }
	  if ( "$pollStatus" ne "" ) {
            #system (" $updateTool seedFile-$remoteUser changeStatus $entry $pollStatus");
            &updateNodeStatus( $entry, "seedFile-$remoteUser", $pollStatus );
	  }
	  if ( "$managementType" ne "" ) {
            #system (" $updateTool seedFile-$remoteUser modManType $entry $managementType");
            &setManType( $entry, "seedFile-$remoteUser", $managementType);
	  }
          my $ipDir = getIpDir( $entry ) ;
          if ( ! -d $ipDir ) {
            print("node $entry not added, specify a type above.");
          }
        } elsif ( "$importAction" eq "remove" ) {
          &removeIp( $entry, "seedFile-$remoteUser" );
	  # system (" $updateTool seedFile-$remoteUser removeEntry $entry");
	} elsif ( "$importAction" eq "sla" ) {
          print("no ip sla monitor $num\n");
          $slaInfo = "$slaInfo ip sla monitor $num
                   type echo protocol ipIcmpEcho $entry
                   request-data-size 64
                   timeout 4000
                   frequency 300
                 ip sla monitor schedule $num life forever start-time now\n!\n";
          $num++;
        } else {
          printNodeLine( $entry );
          $testList = "$testList $entry";
        }
      }
    }
    if ( "$importAction" eq "test" ) {
      print("</TABLE>
             <H3>Please select the reccord options that need to be changed, or select a different action.</H3>
               <FORM method=post Action=$httpScriptName?$module+$tool+importIp>
	       <INPUT TYPE=hidden NAME=seedList VALUE=\"$testList\">
       <TABLE>
       <TR><TD>Node type:</TD><TD><SELECT NAME=nodeType size=1>
                  <OPTION VALUE=>Select device type</option>");
      open(INFO, "$sharedConfDir/nodeTypes");
      my @lines = <INFO>;
      close(INFO);
      foreach my $regel (@lines) {
        chomp $regel;
        my ( $prefix, $type, $color, $default, $pollType, $dnsType, $description ) = split(' ', $regel, 7);
        if ( "$prefix" eq "nodeType" ) {
          print("<OPTION VALUE=$type>$type --- $description</OPTION>");
        }
      }
      print("</SELECT></TD><TD><I>optional</I></TD></TR>
          <TR><TD>Reccord type:</TD><TD><SELECT NAME=recType size=1>
                     <OPTION VALUE=>Select reccord type</OPTION>");
      while ( my ($key, $value) = each(%recColor) ) {
        print("<OPTION VALUE=$key>$key</OPTION>");
      }
      print("</SELECT></TD><TD><I>optional</I></TD></TR>
          <TR><TD>Poll status:</TD><TD><SELECT NAME=pollStatus size=1>
                     <OPTION VALUE=>Select poll status</OPTION>");
      while ( my ($key, $value) = each(%ipColor) ) {
        print("<OPTION VALUE=$key>$key</OPTION>");
      }
      print("</SELECT></TD><TD><I>optional</I></TD></TR>
           <TR><TD>Management type:</TD><TD><SELECT NAME=managementType size=1>
                     <OPTION VALUE=>Select management type</OPTION>");
      while ( my ($key, $value) = each(%manAbrev) ) {
        print("<OPTION VALUE=$key>$key</OPTION>");
      }
      print("</SELECT></TD><TD><I>optional</I></TD></TR>

           <TR><TD>Action:</TD><TD><SELECT NAME=action SIZE=1>
	         <OPTION VALUE=test>Please select your action</OPTION>
	         <OPTION VALUE=import>import (import entries to the database)</OPTION>
		 <OPTION VALUE=sla>sla (create ip sla monitor icmp echo entries)</OPTION>
		 <OPTION VALUE=remove>Remove nodes (BE CAREFULL!!!!!!)</OPTION>
		   </SELECT></TD></TR>
             </TABLE>
	       <INPUT TYPE=submit Value=\"Process\">
	       </FORM>
            ");
    } elsif ( "$importAction" eq "sla" ) {
      print("<HR>$slaInfo</PRE>");
    }

  }
}

# ------------------------------------- Main ---------------------------------------

&printMainMenu;
if ( "$action" eq "importIp" ) {
  importIp;
} elsif ( "$action" eq "importArp" ) {
  importArp;
} else {
  print("Select an option from the above menu.");
}
#&printFooter;
